// server/api/studies.get.ts
import { defineEventHandler, getQuery } from "h3";
import { verifyToken } from "../../utils/auth";
import prisma from "../../utils/prisma";

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, "authorization");
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      throw createError({ statusCode: 401, message: "未提供认证令牌" });
    }

    const token = authHeader.slice(7);
    const decoded = verifyToken(token);
    if (!decoded) {
      throw createError({ statusCode: 401, message: "令牌无效或已过期" });
    }

    // 获取查询参数
    const query = getQuery(event);
    const { 
      username, 
      page = '1',
      limit = '10',
      type, // 可选：按学习类型过滤
      keyword // 可选：按内容关键词搜索
    } = query

    if (!username) {
      throw createError({ statusCode: 400, message: "需要提供用户名参数" });
    }

    const pageNum = parseInt(page as string);
    const limitNum = parseInt(limit as string);
    const skip = (pageNum - 1) * limitNum;

    // 查找用户
    const user = await prisma.user.findUnique({
      where: { username: username as string },
    });

    if (!user) {
      throw createError({ statusCode: 404, message: "用户不存在" });
    }
        // 构建查询条件
        const whereCondition: any = { userId: user.id }
    
        if (type) {
          whereCondition.type = type
        }
        
        if (keyword) {
          whereCondition.OR = [
            { content: { contains: keyword as string } },
            { applicationScenario: { contains: keyword as string } },
            { remark: { contains: keyword as string } }
          ]
        }

    // 并行查询数据总数和分页数据
    const [studies, totalCount] = await Promise.all([
      // 分页查询学习记录
      prisma.study.findMany({
        where: { userId: user.id },
        skip,
        take: limitNum,
        orderBy: { createdAt: "desc" },
        include: {
          user: {
            select: {
              username: true,
              email: true,
            },
          },
        },
      }),
      // 查询总数
      prisma.study.count({
        where: { userId: user.id },
      }),
    ]);

    console.log(`获取到 ${studies.length} 条学习记录，用户ID: ${user.id}`);

    // 计算分页信息
    const totalPages = Math.ceil(totalCount / limitNum);

    return {
      code: 200,
      message: "获取学习记录成功",
      data: {
        studies,
        pagination: {
          currentPage: pageNum,
          pageSize: limitNum,
          totalCount,
          totalPages,
          hasNextPage: pageNum < totalPages,
          hasPrevPage: pageNum > 1,
        },
      },
    };
  } catch (error: any) {
    console.error("获取学习记录失败:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      message: error.message || "获取学习记录失败",
    });
  }
});
